package com.wzy.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.wzy.server.mapper.EmployeeMapper;
import com.wzy.server.mapper.MailLogMapper;
import com.wzy.server.pojo.*;
import com.wzy.server.service.IEmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wzy
 * @since 2021-04-30
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MailLogMapper mailLogMapper;


//    获取所有员工（分页）
    @Override
    public RespPageBean getEmployeeByPage(Integer currentPage, Integer size, Employee employee, LocalDate[] beginDateScope) {
//       开启分页
        Page<Employee> page = new Page<>(currentPage,size);
        IPage<Employee> employeeByPage = employeeMapper.getEmployeeByPage(page,employee,beginDateScope);
        RespPageBean respPageBean = new RespPageBean(employeeByPage.getTotal(),employeeByPage.getRecords());
        return respPageBean;
    }

//    获取最大工号
    @Override
    public RespBean maxWorkID() {
        QueryWrapper<Employee> wrapper=new QueryWrapper<>();
//                                                              获取员工最大id
        List<Map<String,Object>> maps= employeeMapper.selectMaps(wrapper.select("max(workID)"));
//                                           转为string类型  防止字符乱码（不足8位用0补齐）  转为integer类型                             转为字符串  最大员工号加一
        return RespBean.success("最大工号", String.format("%08d",Integer.parseInt(maps.get(0).get("max(workID)").toString())+1));
    }

//    添加员工
    @Override
    public RespBean addEmp(Employee employee) {
        //        处理合同期限，保留两位小数
        LocalDate beginContract = employee.getBeginContract();//合同开始期限
        LocalDate endContract = employee.getEndContract();//合同结束期限
        long days = beginContract.until(endContract, ChronoUnit.DAYS);//计算合同天数
        DecimalFormat decimalFormat = new DecimalFormat("##.00");//保留两位小数
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365.00)));//天数转为年
        if (1 == employeeMapper.insert(employee)){//添加员工
// 发送信息               获取员工对象，通过rabbitMQ发送邮箱
            Employee emp = employeeMapper.getEmployee().get(0);
//            数据库记录发送的消息     消息id
            String msgId = UUID.randomUUID().toString();
            MailLog mailLog=new MailLog();
            mailLog.setMsgId(msgId);//消息id
            mailLog.setEid(employee.getId());//员工id
            mailLog.setStatus(0);//状态
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);//路由key
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);//交换机
            mailLog.setCount(0);//重复次数
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));//重试时间（当前时间加1分钟）
            mailLog.setCreateTime(LocalDateTime.now());//创建时间
            mailLog.setUpdateTime(LocalDateTime.now());//更新时间
            mailLogMapper.insert(mailLog);//消息入库
// 发送信息                                                                      路由key                                          id
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME,emp,new CorrelationData(msgId));
            return RespBean.success("添加成功！");
        }
        return RespBean.error("添加失败！");
    }


//    查询员工
    @Override
    public List<Employee> getEmployee(Integer id) {
        return employeeMapper.getEmployee();
    }

//    获取所有工资账套
    @Override
    public RespPageBean getEmployeeWithSalary(Integer currentPage, Integer size) {
        Page<Employee>page=new Page<>(currentPage,size);//开启分页
        IPage<Employee>employeeIPage = employeeMapper.getEmployeeWithSalary(page);//获取分页
        RespPageBean respPageBean = new RespPageBean(employeeIPage.getTotal(),employeeIPage.getRecords());//传入条数和数据
        return respPageBean;
    }


}

